//
//  AppDelegate+APPService.m
//  BCBDemo
//
//  Created by wukong on 2018/9/18.
//  Copyright © 2018年 BCB. All rights reserved.
//

#import "AppDelegate+APPService.h"
#import "BaseNavigationViewController.h"
#import "RGLoginViewController.h"
#import <IQKeyboardManager.h>
#import <TXLiteAVSDK_UGC/TXLiveBase.h>
#import <AFNetworking.h>
#import <Bugly/Bugly.h>

@implementation AppDelegate (APPService)

#pragma mark ————— 初始化服务 —————
-(void)initService{
    //注册登录状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNotificationLoginStateChange
                                               object:nil];
    //网络状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(netWorkStateChange:)
                                                 name:KNotificationNetWorkStateChange
                                               object:nil];
    //键盘
      [IQKeyboardManager sharedManager].enable = YES;
    [self initBugly];
}

-(void) initBugly{
    
    BuglyConfig *config = [[BuglyConfig alloc] init];
    config.debugMode = YES;
    [Bugly startWithAppId:@"d77dc674f1"
#ifdef DEBUG
        developmentDevice:YES
#endif
                   config:config];
}

#pragma mark ————— 初始化window —————
-(void)initWindow{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = KWhiteColor;
    [self.window makeKeyAndVisible];
    [[UIButton appearance] setExclusiveTouch:YES];
        [[UIButton appearance] setShowsTouchWhenHighlighted:YES];
//    [UIActivityIndicatorView appearanceWhenContainedIn:[MBProgressHUD class], nil].color = KWhiteColor;
    if (@available(iOS 11.0, *)){
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
}

#pragma mark ————— 初始化用户系统 —————
-(void)initUserManager{
    
    NSString *token = [RGUserInfoModel getUserInfo].token;
    if(token.length){
        KPostNotification(KNotificationLoginStateChange, @YES);
    }else{
        KPostNotification(KNotificationLoginStateChange, @NO);
    }

}

-(void) initShortVideoConfig{
    [TXUGCBase setLicenceURL:@"http://license.vod2.myqcloud.com/license/v1/1aeefbcc3df028d8ac38678372ff0484/TXUgcSDK.licence" key:@"7fce195f2e48ac4de387cac96248f7c6"];
}

#pragma mark ————— 登录状态处理 —————
- (void)loginStateChange:(NSNotification *)notification
{
    BOOL loginSuccess = [notification.object boolValue];
    
    if (loginSuccess) {//登陆成功加载主窗口控制器
        
        //为避免自动登录成功刷新tabbar
        if (!self.mainTabBar || ![self.window.rootViewController isKindOfClass:[RGTabBarViewController class]]) {
            if(self.mainTabBar == nil){
                self.mainTabBar = [RGTabBarViewController new];
            }
           
//            CATransition *anima = [CATransition animation];
//            anima.type = @"cube";//设置动画的类型
//            anima.subtype = kCATransitionFromRight; //设置动画的方向
//            anima.duration = 0.3f;
            self.window.rootViewController = self.mainTabBar;

//            [kAppWindow.layer addAnimation:anima forKey:@"revealAnimation"];

        }
        
    }else {//登陆失败加载登陆页面控制器
        
//        self.mainTabBar = nil;
        BaseNavigationViewController *loginNavi =[[BaseNavigationViewController alloc] initWithRootViewController:[RGLoginViewController new]];
//
////        CATransition *anima = [CATransition animation];
////        anima.type = @"fade";//设置动画的类型
////        anima.subtype = kCATransitionFromRight; //设置动画的方向
////        anima.duration = 0.3f;
        self.window.rootViewController = loginNavi;
////        [kAppWindow.layer addAnimation:anima forKey:@"revealAnimation"];
        
    }
}

-(void) resetTabarViewWithSelectIndex:(NSInteger)index{
//    self.mainTabBar = nil;
//    self.mainTabBar = [BCBTabBarViewController new];
//    //            CATransition *anima = [CATransition animation];
//    //            anima.type = @"cube";//设置动画的类型
//    //            anima.subtype = kCATransitionFromRight; //设置动画的方向
//    //            anima.duration = 0.3f;
//    if([[self.mainTabBar viewControllers] count] > index){
//        self.mainTabBar.selectedIndex = index;
//    }
//    self.window.rootViewController = self.mainTabBar;
}


-(void)changeTabbarUiStyleWithIsClear:(BOOL)isClear{
    
    if(self.mainTabBar){
//       [self.mainTabBar changeTabbarUiStyleWithShowClear:isClear];
    }
}


#pragma mark ————— 网络状态变化 —————
- (void)netWorkStateChange:(NSNotification *)notification
{
//    BOOL isNetWork = [notification.object boolValue];
//
//    if (isNetWork) {//有网络
//        if ([userManager loadUserInfo] && !isLogin) {//有用户数据 并且 未登录成功 重新来一次自动登录
//            [userManager autoLoginToServer:^(BOOL success, NSString *des) {
//                if (success) {
//                    DLog(WKLocalized(@"网络改变后，自动登录成功", nil));
//                    //                    [MBProgressHUD showSuccessMessage:WKLocalized(@"网络改变后，自动登录成功", nil)];
//                    KPostNotification(KNotificationAutoLoginSuccess, nil);
//                }else{
//                    [MBProgressHUD showErrorMessage:NSStringFormat(WKLocalized(@"自动登录失败：%@", nil),des)];
//                }
//            }];
//        }
//
//    }else {//登陆失败加载登陆页面控制器
//        [MBProgressHUD showTopTipMessage:WKLocalized(@"网络状态不佳", nil) isWindow:YES];
//    }
}

#pragma mark ————— OpenURL 回调 —————
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    
    //    if(url.host.length == 0){
    //        return [ShareSDK :url
    //                            wxDelegate:self];
    //    }
    return YES;
    //    return  [WXApi handleOpenURL:url delegate:[XLMShareSdkTool shareInstance]];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    //    if(url.host.length == 0){
    //        return [ShareSDK handleOpenURL:url
    //                     sourceApplication:sourceApplication
    //                            annotation:annotation
    //                            wxDelegate:self];
    //    }
    //    return [WXApi handleOpenURL:url delegate:[XLMShareSdkTool shareInstance]];
    return YES;
}

-(BOOL)application:(UIApplication*)app openURL:(NSURL*)url options:(NSDictionary<NSString *,id> *)options{
    NSLog(@"ee");
    //    NSString *SourceApplicationKey = [options objectForKey:@"UIApplicationOpenURLOptionsSourceApplicationKey"];
    //    if([SourceApplicationKey isEqualToString:@"com.tencent.xin"] && [url.host isEqualToString:@"oauth"]){
    //        NSString *code = [XLMToolBox makeAuthCodeWithUrl:url.absoluteString];
    //        if(code.length){
    //            [[NSUserDefaults standardUserDefaults] setObject:code forKey:XLMThirdLoginWithWeChatCode];
    //            [[NSUserDefaults standardUserDefaults] synchronize];
    //        }
    //    }
    //
    //    return YES;
    
    return  [WXApi handleOpenURL:url delegate:[XLMShareSdkTool shareInstance]];
    
}

#pragma mark ————— 网络状态监听 —————
- (void)monitorNetworkStatus
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                
                break;
            case AFNetworkReachabilityStatusNotReachable:
                
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationNetWorkStateChange object:nil];
                break;
        }
    }];
    
}

+ (AppDelegate *)shareAppDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

-(void) reInitTabarViewController{

    self.mainTabBar = nil;
}


-(UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

-(UIViewController *)getCurrentUIVC
{
    UIViewController  *superVC = [self getCurrentVC];
    
    if ([superVC isKindOfClass:[UITabBarController class]]) {
        
        UIViewController  *tabSelectVC = ((UITabBarController*)superVC).selectedViewController;
        
        if ([tabSelectVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)tabSelectVC).viewControllers.lastObject;
        }
        return tabSelectVC;
    }else
        if ([superVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)superVC).viewControllers.lastObject;
        }
    return superVC;
}

-(void) initShareSdk{
    [XLMShareSdkTool registerShare];
}

@end
